import Vue from "vue";
import Router from "vue-router";
import Login from "@/pages/Login";
import Main from "@/pages/Main";
import NewsTypeList from "@/components/main/NewsTypeList";


// 引入Vuex数据，方便获取是否登录的状态
import store from "@/store/index";
Vue.use(Router);
const router = new Router({
  routes: [
    {
      path: "/",
      name: "Login",
      component: Login,
    },
    {
      path: "/login",
      name: "Login",
      component: Login,
    },
    {
      path: "/main",
      name: "Main",
      component: Main,
      children: [
        {
          path: "/news-type/list",
          name: "NewsTypeList",
          component: NewsTypeList,
        },
      ],
    },
  ],
});

// 全局路由守卫,控制权限
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    // 从store中获取用户登录信息
    let isLogin = store.state.userStore.isLogin;
    // 判断用户是否登录
    if (!isLogin) {
      // 提示未登录
      Vue.prototype.$message.error("无权访问，请先登录！");
      // 未登录进行拦截，跳转到登录页面
      next("/login");
    } else {
      next();
    }
  }
})
// 导出router对象
export default router;

